package com.zxb.core.util;

import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.google.code.kaptcha.util.Config;
import com.zxb.core.common.C;

import javax.imageio.ImageIO;
import javax.script.ScriptException;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Base64;
import java.util.Properties;

/**
 * @author Zxb
 */
public class KaptchaUtil {
    public static DefaultKaptcha getDefaultKaptcha(){
        DefaultKaptcha defaultKaptcha = new DefaultKaptcha();
        Properties properties = new Properties();
        properties.setProperty("kaptcha.border", "yes");
        properties.setProperty("kaptcha.border.color", "105,179,90");
        properties.setProperty("kaptcha.textproducer.font.color", "blue");
        properties.setProperty("kaptcha.image.width", "140");
        properties.setProperty("kaptcha.image.height", "40");
        properties.setProperty("kaptcha.textproducer.font.size", "30");
        properties.setProperty("kaptcha.session.key", "captcha");
        properties.setProperty("kaptcha.textproducer.char.length", "4");
        properties.setProperty("kaptcha.textproducer.font.names", "宋体,楷体,微软雅黑");
        // properties.setProperty("kaptcha.background.impl","com.it.core.web.CustomBackground");
        Config config = new Config(properties);
        defaultKaptcha.setConfig(config);
        return defaultKaptcha;
    }

    public static String[] generate() throws ScriptException {
        DefaultKaptcha kaptcha = KaptchaUtil.getDefaultKaptcha();
        String[] strArr = new String[2];
        String[] verificationCode = NumericalExpUtil.getVerificationCode();
        BufferedImage image = kaptcha.createImage(verificationCode[0]);
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        try {
            ImageIO.write(image, "jpg", outputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
        Base64.Encoder encoder = Base64.getEncoder();
        String base64Img = encoder.encodeToString(outputStream.toByteArray());
        strArr[0] = SecureUtil.md5(verificationCode[1] + C.SALT);
        strArr[1] = base64Img;
        return strArr;
    }

    public static Boolean validate(String sign, String captcha) {
        return StrUtil.isNotEmpty(sign)
                && StrUtil.isNotEmpty(captcha)
                && SecureUtil.md5(captcha + C.SALT).equals(sign);
    }
}
